#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库结构查看器 - 放在OperatingSystem目录下直接使用
"""

from database_server import DatabaseServer, DatabaseConfig
from storage_engine import CachePolicy

def main():
    """数据库查看器主函数"""
    print("🔍 数据库结构查看器")
    print("=" * 50)
    
    try:
        # 使用相对路径，从OperatingSystem目录运行
        config = DatabaseConfig(
            db_path="./demo_data",
            cache_size=50,
            cache_policy=CachePolicy.LRU,
            enable_locking=False
        )
        
        print("🚀 正在启动数据库服务器...")
        server = DatabaseServer(config)
        server.start()
        session = server.create_session()
        print("✅ 服务器启动成功！")
        
        print("\n选择模式:")
        print("1. 查看所有数据库结构")
        print("2. 交互式查看")
        
        choice = input("\n请选择 (1 或 2): ").strip()
        
        if choice == '1':
            # 显示所有结构
            show_all_structure(server, session)
        elif choice == '2':
            # 交互模式
            interactive_mode(server, session)
        else:
            print("❌ 无效选择")
        
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        try:
            server.stop()
            print("🛑 服务器已停止")
        except:
            pass

def show_all_structure(server, session):
    """显示所有数据库结构"""
    print("\n🔍 完整数据库结构")
    print("=" * 60)
    
    try:
        databases = server.list_databases(session)
        
        if not databases:
            print("💡 系统中暂无数据库")
            return
        
        print(f"📊 找到 {len(databases)} 个数据库\n")
        
        for i, db_name in enumerate(databases, 1):
            print(f"{i}. 📁 数据库: {db_name}")
            print("-" * 40)
            
            try:
                server.use_database(session, db_name)
                db_instance = server.database_manager.get_database(db_name)
                tables = db_instance.list_tables()
                
                if not tables:
                    print("   💡 此数据库中暂无表\n")
                    continue
                
                print(f"   📋 表数量: {len(tables)}")
                
                for j, table_name in enumerate(tables, 1):
                    print(f"\n   {j}. 表: {table_name}")
                    
                    # 获取表结构
                    schema = db_instance.storage_engine.table_schemas.get(table_name)
                    if schema:
                        print(f"      字段 ({len(schema.columns)} 个):")
                        for col in schema.columns:
                            pk_mark = " (主键)" if col.primary_key else ""
                            length_info = f"({col.length})" if col.length else ""
                            print(f"        - {col.name}: {col.type.name}{length_info}{pk_mark}")
                        
                        # 获取记录数和示例
                        records = db_instance.select_records(table_name)
                        print(f"      记录数: {len(records)}")
                        
                        if records:
                            print("      数据示例:")
                            for idx, record in enumerate(records[:3], 1):
                                print(f"        {idx}. {record}")
                            if len(records) > 3:
                                print(f"        ... 还有 {len(records) - 3} 条记录")
                    else:
                        print("      ❌ 无法获取表结构")
                
                print()
                
            except Exception as e:
                print(f"   ❌ 分析数据库失败: {e}\n")
        
    except Exception as e:
        print(f"❌ 获取数据库列表失败: {e}")

def interactive_mode(server, session):
    """交互式模式"""
    print("\n🔍 交互式数据库查看器")
    print("=" * 50)
    
    print("可用命令:")
    print("  show databases - 显示所有数据库")
    print("  use <db_name>  - 切换数据库")
    print("  show tables    - 显示表列表")
    print("  desc <table>   - 显示表结构")
    print("  select <table> [limit] - 显示表数据")
    print("  help           - 显示帮助")
    print("  quit           - 退出")
    print()
    
    current_db = None
    
    while True:
        try:
            prompt = f"({current_db if current_db else 'none'}) > "
            command = input(prompt).strip()
            
            if not command:
                continue
            
            parts = command.split()
            cmd = parts[0].lower()
            
            if cmd == 'quit':
                break
            elif cmd == 'help':
                print("\n可用命令:")
                print("  show databases - 显示所有数据库")
                print("  use <db_name>  - 切换数据库")
                print("  show tables    - 显示表列表")
                print("  desc <table>   - 显示表结构")
                print("  select <table> [limit] - 显示表数据")
                print("  quit           - 退出\n")
            elif cmd == 'show':
                if len(parts) >= 2:
                    sub_cmd = parts[1].lower()
                    if sub_cmd == 'databases':
                        databases = server.list_databases(session)
                        print(f"\n📊 数据库列表:")
                        if databases:
                            for i, db_name in enumerate(databases, 1):
                                print(f"  {i}. 📁 {db_name}")
                        else:
                            print("  💡 暂无数据库")
                        print()
                    elif sub_cmd == 'tables':
                        if current_db:
                            db_instance = server.database_manager.get_database(current_db)
                            tables = db_instance.list_tables()
                            print(f"\n📋 数据库 '{current_db}' 中的表:")
                            if tables:
                                for i, table_name in enumerate(tables, 1):
                                    records = db_instance.select_records(table_name)
                                    print(f"  {i}. 📊 {table_name} ({len(records)} 条记录)")
                            else:
                                print("  💡 暂无表")
                            print()
                        else:
                            print("❌ 请先选择数据库\n")
                    else:
                        print("❌ 未知的 show 命令，支持: databases, tables\n")
                else:
                    print("❌ show 命令需要参数\n")
            elif cmd == 'use':
                if len(parts) >= 2:
                    db_name = parts[1]
                    try:
                        server.use_database(session, db_name)
                        current_db = db_name
                        print(f"✅ 已切换到数据库: {db_name}\n")
                    except Exception as e:
                        print(f"❌ 切换失败: {e}\n")
                else:
                    print("❌ 请指定数据库名称\n")
            elif cmd == 'desc':
                if len(parts) >= 2:
                    table_name = parts[1]
                    if current_db:
                        try:
                            db_instance = server.database_manager.get_database(current_db)
                            schema = db_instance.storage_engine.table_schemas.get(table_name)
                            if schema:
                                print(f"\n📋 表结构: {current_db}.{table_name}")
                                print("=" * 50)
                                print(f"{'字段名':<15} {'类型':<12} {'长度':<8} {'主键':<6}")
                                print("-" * 50)
                                for col in schema.columns:
                                    pk_mark = "是" if col.primary_key else "否"
                                    length_info = str(col.length) if col.length else "N/A"
                                    print(f"{col.name:<15} {col.type.name:<12} {length_info:<8} {pk_mark:<6}")
                                print()
                            else:
                                print(f"❌ 表 {table_name} 不存在\n")
                        except Exception as e:
                            print(f"❌ 获取表结构失败: {e}\n")
                    else:
                        print("❌ 请先选择数据库\n")
                else:
                    print("❌ 请指定表名称\n")
            elif cmd == 'select':
                if len(parts) >= 2:
                    table_name = parts[1]
                    limit = int(parts[2]) if len(parts) >= 3 and parts[2].isdigit() else 5
                    if current_db:
                        try:
                            db_instance = server.database_manager.get_database(current_db)
                            records = db_instance.select_records(table_name)
                            
                            print(f"\n📊 表数据: {current_db}.{table_name}")
                            print("=" * 50)
                            print(f"总记录数: {len(records)}, 显示前 {min(limit, len(records))} 条\n")
                            
                            if records:
                                for i, record in enumerate(records[:limit], 1):
                                    print(f"{i}. {record}")
                                if len(records) > limit:
                                    print(f"... 还有 {len(records) - limit} 条记录")
                            else:
                                print("💡 表中暂无数据")
                            print()
                        except Exception as e:
                            print(f"❌ 查询失败: {e}\n")
                    else:
                        print("❌ 请先选择数据库\n")
                else:
                    print("❌ 请指定表名称\n")
            else:
                print(f"❌ 未知命令: {command}")
                print("💡 输入 'help' 查看可用命令\n")
                
        except KeyboardInterrupt:
            print("\n👋 退出程序")
            break
        except EOFError:
            print("\n👋 退出程序")
            break

if __name__ == "__main__":
    main()
